package com.tienon.message.mq;

import java.util.Random;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import com.ibm.mq.jms.MQQueueConnectionFactory;

public class JMSReceiver {

	private static MQQueueConnectionFactory mcf;

	private static Connection conn;

	private Session session;

	private static Session[] sessions;

	private Destination dest;

	private MessageConsumer consumer;
	private static Random rand;

	static {
		rand = new Random();

		try {
			mcf = new MQQueueConnectionFactory();
			mcf.setQueueManager("AppMsg");
			mcf.setHostName("www.xiuye.com");
			mcf.setPort(1417);
			conn = mcf.createConnection();
			conn.start();
			sessions = new Session[50];
			for (int i = 0; i < sessions.length; i++) {
				sessions[i] = conn
						.createSession(true, Session.AUTO_ACKNOWLEDGE);
			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public String receiveMsg() throws JMSException {

		session = sessions[rand.nextInt(sessions.length)];
		
		dest = session.createQueue("SendMsg");
		consumer = session.createConsumer(dest);

		TextMessage msg = (TextMessage) this.consumer.receive();

		return msg.getText();

	}

	public static void main(String[] args) {

		JMSReceiver receiver = new JMSReceiver();
		try {
			while (true) {

				String msg = receiver.receiveMsg();
				System.out.println(msg);

			}
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
